var app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  data: {
    showsb:false,
    showgif:true,
    errorflag:false,
    errorflag2:false,
    errorflag4:false,
    errorflag5:false,
    gowhere:0, //1班次申请 2结算申请
    sbflag:false,
    quanxian:'',
    sbstatushtml:'',
    sbstatus:'',
    isWxapp: true,
    isLogin: false,
    sssb:false,
    sssb2:false,
    title:'请先登录账号',
    banci:false,
    jsstyle:'',
    quanxian:false,
    userInfo: {
      id: 0,
      avatarUrl: '/assets/images/avatar.png',
      nickName: '未登录',
      balance: 0,
      score: 0,
      ccc:1,
      level: 0,
    },
  },
  onLoad: function () {
    qqmapsdk = new QQMapWX({
      key: 'S3OBZ-YGPW2-VSFUH-CGEKB-RUVPS-PMFKF'
  });

  },
  onShow: function () {
    var that = this;
    if (wx.getStorageSync('userInfo')) {
      that.setData({ userInfo: wx.getStorageSync('userInfo'), isWxapp: that.isWxapp(), isLogin:true });
      //实时判断是否有考勤异常需要处理
      that.getopenid();
    }else{
        //未登录 隐藏考勤异常 和 异常处理
        that.setData({ showgif: false});
        that.setData({ errorflag: false});
        that.setData({ errorflag2: false});
    }
    
  },
  onReady:function(){
   
  },

  //获取个人信息
 getinfo(){
    var that = this;
    wx.request({
      url: app.apiUrl + '/api/index/getinfo',
      data: {
        openid:wx.getStorageSync('openid'),
      },
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: res=> {
        wx.setStorageSync('userInfo',res.data.data)
        that.setData({ userInfo: wx.getStorageSync('userInfo'), isWxapp: that.isWxapp(), isLogin:true });

      }
    })
  },
  //考勤异常 个人
  errorlistone(){
    var that =this
      wx.request({
        url: app.apiUrl + '/api/index/errorlistone',
        data: {
          openid:wx.getStorageSync('openid'),
        },
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: res=> {
          if(res.data.code == "1"){
            var len = res.data.data.count;
            var sbflag = res.data.data.sbflag;
            that.setData({ sbflag: sbflag});
            if(len > 0){
              that.setData({ errorflag2: true});
            }else{
              that.setData({ errorflag2: false});
            }
          }
          
        }
      })
  },
    //班次&结算
    appdata(){
      var that =this
        wx.request({
          url: app.apiUrl + '/api/index/appdata',
          data: {},
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: res=> {
            //结算
            if(res.data.data.wcount > 0){
              that.setData({ errorflag4: true,gowhere:2}); 
            }
            //班次
            if(res.data.data.bcount > 0){
              that.setData({ errorflag4: true,gowhere:1}); 
            }
            //都没有
            if(res.data.data.bcount == 0 && res.data.data.wcount == 0){
              that.setData({ errorflag4: false,gowhere:0}); 
            }
            console.log(res)
          }
        })
    },
  
  //考勤异常处理
  errorlist(){
      var that =this
        wx.request({
          url: app.apiUrl + '/api/index/errorlist',
          data: {
            openid:wx.getStorageSync('openid'),
          },
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: res=> {
            var len = res.data.data.length;
            if(len > 0){
              that.setData({ errorflag: true});
            }else{
              that.setData({ errorflag: false});
            }
         
          }
        })
    },

  //退料处理
  tuiliao(){
    var that =this
      wx.request({
        url: app.apiUrl + '/api/data/tuiliao',
        data: {
          openid:wx.getStorageSync('openid')
        },
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: res=> {
          var len = res.data.data;
          if(len > 0){
            that.setData({ errorflag5: true});
          }else{
            that.setData({ errorflag5: false});
          }
       
        }
      })
  },


  buqian222(){
    var that = this
    wx.showActionSheet({
      itemList: ['补早班卡', '提前下班'],
      success(res) {

        // console.log(res.tapIndex)1
        if(res.tapIndex == 0){
          //补早班卡
          wx.navigateTo({
            url: 'buka',
          });
        }

        if(res.tapIndex == 1){
            that.zaotui()
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },


  changebanci(){
    var that = this
    wx.showActionSheet({
      itemList: ['早班', '晚班'],
      success(res) {

        // console.log(res.tapIndex)1
        if(res.tapIndex == 0){
          that.changebc(1)
        }


        if(res.tapIndex == 1){
          that.changebc(2)
        }


      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },


  qingjia(){
    var that = this
    wx.showActionSheet({
      //itemList: ['按天请假', '按小时请假','申请补卡'],
      itemList: ['按天请假', '按小时请假'],
      success(res) {

        if(res.tapIndex == 0){

          wx.navigateTo({
            url: '/page/my/antian',
          });
        }


        if(res.tapIndex == 1){
       wx.navigateTo({
            url: '/page/my/anshi',
          });
        }

        
        if(res.tapIndex == 2){
          wx.navigateTo({
               url: '/page/my/buka',
             });
           }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },


  getopenid() {

    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: app.apiUrl + '/api/index/getopenid',
          data: {
            code: res.code,
            avatarUrl:wx.getStorageSync('userInfo').avatarUrl,
            nickname:wx.getStorageSync('userInfo').nickName
          },
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: res=> {
            wx.setStorageSync('openid',res.data.openid)
            this.getinfo()
            this.checktitle()
            this.getbanci()
            this.getgroup()
            this.errorlist();
            this.errorlistone(); 
            this.tuiliao();   
            this.appdata();  

          }
        })
      }
    })
},
  login: function () {
    var that = this;
    that.setData({showgif:true});
    wx.getUserProfile({
      lang:'zh',
      desc:'授权用户信息',
      success:function(res){
        that.getopenid();
        that.errorlist();
        that.errorlistone();  
        that.tuiliao();   
      },
      fail:function(e){
        console.log("jsw")
        console.log(JSON.stringify(e))
        console.log("jsw")

        app.info(JSON.stringify(e));
      }
    })
  },
  logout: function () {
    var that = this;
    wx.clearStorage();
    wx.clearStorageSync();
      that.setData({ userInfo: {
          id: 0,
          avatar: '/assets/images/avatar.png',
          nickName: '未登陆',
          balance: 0,
          score: 0,
          level: 0
        }, isWxapp: that.isWxapp(), isLogin: false,title:'请先登陆账号' });
   
  },
  isWxapp: function () {
    return app.globalData.userInfo ? app.globalData.userInfo.username.match(/^u\d+$/) : true;
  },
  //只有超管和主任可以处理异常考勤
  zgerror:function(){
    wx.navigateTo({
      url: '/page/my/errorkq',
    })
  },
    //只有超管和主任可以处理退料申请
    zgerror3:function(){
      wx.navigateTo({
        url: '/page/my/tuiliaojilu',
      })
    },
    //只有超管和主任 跳转 到班次或者结算列表
    zgerror2:function(){
      if(this.data.gowhere == "1"){
        wx.navigateTo({
          url: '/page/my/bancishengqing',
        })
      }else{
        wx.navigateTo({
          url: '/page/my/huanbanjilu',
        })
      }
    },
  //考勤异常 直接跳转到 考勤列表
  zgerrorone:function(){
    wx.navigateTo({
      url: '/page/my/aboutus',
    })
  },

  changebc: function (bc) {
    var that = this;
    console.log(bc)
    wx.request({
      url: app.apiUrl + '/api/index/changebc',
      data: {
        openid:wx.getStorageSync('openid'),
        bc:bc,
        groupid:wx.getStorageSync('groupid')
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
        console.log(res)
        if(res.statusCode == 200){
          wx.showModal({
               title: '温馨提示',
                  //  content: '申请已提交,请等待上级审核',
                  content: '班次调整申请已提交,等待审核',
                    showCancel: false
               });
               that.getbanci()
        }
     
      }
    });
  },
  checktitle: function () {
    var that = this;
    wx.request({
      url: app.apiUrl + '/api/index/checktitle',
      data: {
        openid:wx.getStorageSync('openid'),
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
        if(res.data){
          that.setData({ title: res.data});
          wx.setStorageSync('title',res.data)
        }else{
          that.setData({ title:'未绑定账号或账号无权限,请先完善个人资料'});
        }
     
      },
      error: function (res) {
        that.setData({ title:'未绑定账号或账号无权限,请先完善个人资料'});
      }
    });
  },


  getgroup: function () {
    var that = this;
    wx.request({
      url: app.apiUrl + '/api/index/getgroup',
      data: {
        openid:wx.getStorageSync('openid'),
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
        if(res.data){
          wx.setStorageSync('groupid',res.data.data.group_id)
          wx.setStorageSync('quanxian',res.data.data.quanxian)
          that.setData({ quanxian:res.data.data.quanxian});
          console.log('quanxian',that.data.quanxian)
          if(that.data.quanxian == "1" || that.data.quanxian == "2" ||  that.data.quanxian == "3" ){
            that.setData({ quanxian:true});
          }
        }
      },
      error: function (res) {
        that.setData({ title:'未绑定账号或账号无权限,请先完善个人资料'});
      }
    });
  },

  getbanci: function () {
    var that = this;

    wx.request({
      url: app.apiUrl + '/api/index/jswgetbanci',
      data: {
        openid:wx.getStorageSync('openid'),
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success: function (res) {
          if(res.data.code == 0){
            //去完善资料
            wx.navigateTo({
              url: '/page/my/profile',
            })
            return false;
          }else{
            that.setData({ sbstatushtml: res.data.data.sbstatushtml,sbstatus:res.data.data.sbstatus,banci:res.data.data.banci});
            wx.setStorageSync('nowbc',res.data.data.banci)
            wx.setStorageSync('banci',res.data.data.banci)
            that.getMethod(res.data.data.banci);
          }
     
      }
    });
  },
  //结算方式
  getMethod: function (ban) {
    var that = this;
    wx.request({
      url: app.apiUrl + '/api/index/jswgetMetho2',
      data: {
        openid:wx.getStorageSync('openid'),
        ban:ban,
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success: function (res) { 
        if(res.data.code == 1){
          wx.setStorageSync('jswstyle',res.data.data.style)
          that.setData({ jsstyle: res.data.data.stylename});
          //最后一个接口执行完 关闭 加载 图标
          that.setData({ showgif:false });
        }
      }
    });
  },

  //跳转到考勤列表
  gotokq:function(){
    wx.navigateTo({
      url: '/page/my/aboutus',
    })
  },

  //上班签到
  shangban2: function () { 
    var that = this;
    if (!wx.getStorageSync('openid')) {
      app.error("请登录后再操作");
      return false;
    }
    if(that.data.sbstatus == '0'){
      wx.showModal({
        title: '温馨提示',
        content: '您已经上班，无需重新上班签到',
        showCancel: false
      });
      return false;
    }

    if(that.data.sbstatus == '3'){
      wx.showModal({
        title: '温馨提示',
        content: '您当前考勤异常,点击“考勤记录”,申请处理',
        showCancel: false
      });
      return false;
    }

    if(that.data.sbstatus == '5'){
      wx.showModal({
        title: '温馨提示',
        content: '您申请的班次切换还未审核，请审核后再操作！',
        showCancel: false
      });
      return false;
    }
    if(that.data.sbstatus == '6'){
      wx.showModal({
        title: '温馨提示',
        content: '您申请结算方式变更还未审核，请审核后再操作！',
        showCancel: false
      });
      return false;
    }
    that.setData({showsb:true});
    that.setData({showgif:true});

    qqmapsdk.reverseGeocoder({//SDK调用 不传经纬度则为实时地址
      success: function (res) {
       var juli = that.getDistance(res.result.location.lat,res.result.location.lng)
        if(juli >= '1.5'){
          var status = 3
        }else{
          var status = 0
        }
        var dizhi = res.result.address
  
        wx.request({
          url: app.apiUrl + '/api/index/jswshangban',
          data: {
            openid: wx.getStorageSync('openid'),
            dizhi:dizhi,
            status:status
          },
          method: 'POST',
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          success: res=> {
                that.setData({showgif:false});
                that.setData({showsb:false});
                if(res.data.code == "0"){
                  wx.showModal({
                    title: '温馨提示',
                    content: res.data.msg,
                    showCancel: false
                  });
                  return false;
                }else{
                  wx.showModal({
                    title: '温馨提示',
                    content: res.data.msg,
                    showCancel: false
                  });
                  that.setData({ sbstatushtml: res.data.data.sbstatushtml,sbstatus:res.data.data.sbstatus});
                }
          
 
          }
        })
      },
      fail: function(res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  Rad: function(d) { //根据经纬度判断距离
    return d * Math.PI / 180.0;
},

getDistance: function(lat1, lng1) {
  //固定打卡地址
    var lat2 = '28.480485'
    var lng2 = '121.36329'

    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(4)//保留两位小数
    console.log('经纬度计算的距离:' + s)
    return s
},

  
  xiaban: function () {
    var that = this;
    if (!wx.getStorageSync('openid')) {
      app.error("请登录后再操作");
      return false;
    }
    if(that.data.sbstatus != '0'){
      wx.showModal({
        title: '温馨提示',
        content: '您当前不在上班状态，不能下班，请先上班签到',
        showCancel: false
      });
      return false;
    }
    wx.showModal({
      'title':'温馨提示',
      content:'下班后如需继续工作，需要重新申请上班',
      success:function(sm){
        if(sm.confirm){
          that.setData({showgif:true});
          //执行下班 先要判断是否上班 地址是否异常 是否有临时申请 是否有班次切换申请 
            qqmapsdk.reverseGeocoder({//SDK调用
              success: function (res) {
                var juli = that.getDistance(res.result.location.lat,res.result.location.lng)
                if(juli >= '1.5'){
                  var status = 3
                }else{
                  var status = 0
                }
                var dizhi = res.result.address
                var content = '打卡失败'
                wx.request({
                  url: app.apiUrl + '/api/index/jswxiaban',
                  data: {
                    openid: wx.getStorageSync('openid'),
                    dizhi:dizhi,
                    status:status
                  },
                  method: 'POST',
                  header: { 'content-type': 'application/x-www-form-urlencoded' },
                  success: res=> {
                    that.setData({showgif:false});
                    console.log(res);
                    if(res.data.code == 0){
                      wx.showModal({
                        title: '温馨提示',
                        content: res.data.msg,
                        showCancel: false
                      });
                      return false
                    }else{
                    
                      that.getbanci();
                      that.errorlist();
                      that.errorlistone();  
                      that.tuiliao();  
                      
                      wx.showModal({
                        title: '温馨提示',
                        content: res.data.msg,
                        showCancel: false
                      });
                    }

               
                  }
                })
              }
            })
      
        }else{
          wx.showToast({
            icon:'none',
            title: '您取消了操作！',
          })
          return false;
        }
      }
    })
  },

  zaotui: function () {
    if (!wx.getStorageSync('openid')) {
      app.error("请登录后再操作");
      return false;
    }

    wx.getLocation({
      type: 'wgs84',
      altitude: false,
      success: (res) => {
         var locationString = res.latitude + "," + res.longitude;
          var latitude = res.latitude
          var longitude = res.longitude
          qqmapsdk.reverseGeocoder({//SDK调用
            location: { latitude, longitude },
            success: function (res) {
              console.log(res.result.address)
              var dizhi = res.result.address
              
    var content = '打卡失败'

    wx.request({
      url: app.apiUrl + '/api/index/zaotui',
      data: {
        openid: wx.getStorageSync('openid'),
        dizhi:dizhi
      },
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: res=> {
     
        // wx.showModal({
        //   title: '温馨提示',
        //   content: res.data,
        //   showCancel: false
        // });
      }
    })
            }
          })
      },
    });

  },


  saoyisao: function () {
    var that = this;
    if (!wx.getStorageSync('openid')) {
      app.error("请登录后再操作");
      return false;
    }

    if(this.data.errorflag || this.data.errorflag2){
      wx.showModal({
        title: '温馨提示',
        content: '您当前有申请待处理，不能扫一扫操作!',
        showCancel: false
      });
      return false;
    
  }

  if(that.data.sbstatus == '3'){
    wx.showModal({
      title: '温馨提示',
      content: '考勤审批中，请等待审核！',
      showCancel: false
    });
    return false;
  }

    if(that.data.sbstatus == '5'){
      wx.showModal({
        title: '温馨提示',
        content: '您申请的班次切换还未审核，请审核后再操作！',
        showCancel: false
      });
      return false;
    }
    if(that.data.sbstatus == '6'){
      wx.showModal({
        title: '温馨提示',
        content: '您申请结算方式变更还未审核，请审核后再操作！',
        showCancel: false
      });
      return false;
    }

    if(that.data.sbstatus != '0'){
      app.error("请上班后操作！");
      return false;
    }


    //正常上班 可以操作
    if(that.data.sbstatus == '0'){
      wx.scanCode({
        success (res2) {
          wx.navigateTo({
            //url:res2.path.slice(8)+"_-99",
            url:res2.path.slice(8),
          });
          
        }
      })
    }

    //先判断当前用户在今天是否有签到记录
    // wx.request({
    //   url: app.apiUrl + '/api/index/ifqiandao',
    //   data: {
    //     openid: wx.getStorageSync('openid'),
    //   },
    //   method: 'POST',
    //   header: { 'content-type': 'application/x-www-form-urlencoded' },
    //   success: res=> {
 
    //       if(res.data == 1){
    //         wx.scanCode({
    //           success (res2) {
           
    //             wx.navigateTo({
    //               url:res2.path.slice(8),
    //             });
                
    //           }
    //         })
    //       }else{
    //         wx.showModal({
    //           title: '温馨提示',
    //           content: '请先签到',
    //           showCancel: false
    //         });
    //       }

    //   }
    // })
  },

  showTips: function (event) {
    var tips = {
      balance: '余额',
      score: '积分',
      level: '等级',
    };
    var type = event.currentTarget.dataset.type;
    var content = tips[type];
    wx.showModal({
      title: '温馨提示',
      content: content,
      showCancel: false
    });
  },

  goVip(e){
    if(!this.data.userInfo.is_install_vip){
      app.error('请安装VIP会员插件或启用此插件');
      return;
    }
    if(!this.isLogin){
      app.error('请登录后再操作');
      return;
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },
  goPage(e){
    if(!wx.getStorageSync('userInfo')){
      app.error('请登录后再操作');
      return;
    }

    if(this.data.errorflag || this.data.errorflag2){
        app.error('您当前有申请待处理，不能操作');
        return false;
    }
    if(this.data.sbstatus == "3"){
      app.error('考勤审批中，请等待审核');
      return false;
    }

    if(this.data.sbstatus == "5"){
      app.error('您当前有班次待审核,等审核后操作');
      return false;
    }

    if(this.data.sbstatus == "6"){
      app.error('您当前有变更结算申请待审核,请等审核之后操作');
      return false;
    }
 
      //以下三种情况需要正常上班 才可以执行
      if(this.data.sbstatus == "0"){
        app.error('当前的操作必须下班后操作！');
        return false;
      }
 
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      });
  },
  goPage2(e){
    if(!wx.getStorageSync('userInfo')){
      app.error('请登录后再操作');
      return;
    }

    if(this.data.errorflag || this.data.errorflag2){
        app.error('您当前有申请待处理，不能操作');
        return false;
    }
    if(this.data.sbstatus == "3"){
      app.error('考勤审批中，请等待审核');
      return false;
    }

    if(this.data.sbstatus == "5"){
      app.error('您当前有班次待审核,等审核后操作');
      return false;
    }

    if(this.data.sbstatus == "6"){
      app.error('您当前有变更结算申请待审核,请等审核之后操作');
      return false;
    }
 
      //以下三种情况需要正常上班 才可以执行
      if(this.data.sbstatus == "4"){
        app.error('您还未上班，不能进行变更结算申请！');
        return false;
      }
 
      wx.navigateTo({
        url: e.currentTarget.dataset.url,
      });
  },
  checkLogin(e){
    return;
      console.log(e);
      return false;
  },

  //可以分享转发
  onShareAppMessage: function () {
  
  },
  onShareTimeLine:function(){},
 

})
